import React, { useCallback, useEffect, useState } from 'react'
// import { createForm } from 'rc-form';
import { Modal, List, InputItem, Toast } from 'antd-mobile';

import _http from '@/_http';
import FormMiddleware from '@/components/EditModal'

// let errors

function EditModal({ onOk, editId, rowData, form }) {
  const { getFieldProps, getFieldError, validateFields, setFieldsValue } = form
  const [formData, setFormData] = useState({})
  const [errors, setErrors] = useState([])

  const onClose = useCallback(() => {
    console.log('v');
  }, [])

  useEffect(() => {
    console.log(form, 'form');
    if (rowData) {
      setFieldsValue(rowData, () => console.log('after'));
    }
  }, [rowData])

  return (
    <div>
      <Modal
        visible={true}
        transparent
        maskClosable={false}
        onClose={() => onClose()}
        title={editId ? '修改分类信息' : '添加分类'}
        footer={[
          {
            text: '取消',
            onPress: (e) => {
              console.log('cancel');
              onOk()
            }
          },
          {
            text: editId ? "修改" : '添加',
            onPress: async (e) => {
              validateFields(async (error, value) => {
                console.log(error, 'error');
                if (error) {
                  let keys = Object.keys(error)
                  let errMsg = error[keys[0]].errors
                  setErrors(errMsg[0].message)
                }else{
                  const res = editId ? await _http('/cate/edit', {
                    ...value,
                    catid: editId
                  }, 'post') : await _http('/cate/add', value, 'post')
                  if (res.data.code === 1) {
                    Toast.success(`${editId ? '修改' : '添加'}成功!`)
                  }else{
                    Toast.fail(res.data.msg)
                  }
                  onOk()
                }
              });
            },
          }
        ]}
      >
        <List>
          <InputItem placeholder="请输入分类名" {...getFieldProps('name', {
            onChange() { },
            rules: [{ required: true }],
          })}>分类名</InputItem>
          <InputItem type="number" placeholder="请输入排序" {...getFieldProps('sort')}>排序</InputItem>
          <InputItem placeholder="请输入标记" {...getFieldProps('remark')}>标记</InputItem>
          <div style={{color: 'red'}}>
            {errors || null}
          </div>
        </List>
      </Modal>
    </div>
  )
}


export default FormMiddleware()(EditModal)